import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { SystemAction, SystemSelector } from '../../store';
import { Store } from '@ngxs/store';
import { Navigate } from '@ngxs/router-plugin';

@Injectable({
  providedIn: 'root',
})
export class AuthGuard implements CanActivate {

  constructor(
      private store: Store,
  ) {
  }

  canActivate(
      childRoute: ActivatedRouteSnapshot,
      state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    if (state.url === '/login') {
      return true;
    }
    const user = this.store.selectSnapshot(SystemSelector.user);
    if (!user) {
      this.store.dispatch(new Navigate(['/login']));
      return false;
    }
    return this.store.dispatch(new SystemAction.InitialConfig());
  }
}
